<template>
  <div class="modal">
    <el-dialog v-model="dialogVisible" title="新建数据" width="30%" center>
      <div class="form">
        <el-form :model="formData" label-width="80px" size="large">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入部门名称" />
          </el-form-item>
          <el-form-item label="部门领导" prop="leader">
            <el-input v-model="formData.leader" placeholder="请输入部门领导名称" />
          </el-form-item>
          <el-form-item label="上级部门" prop="parentId">
            <el-select v-model="formData.parentId" placeholder="请选择上级" style="width: 100%">
              <template v-for="item in departmentList" :key="item.id">
                <el-option :value="item.id" :label="item.name" />
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="modal">
import { storeToRefs } from 'pinia'
import { reactive, ref } from 'vue'
import useSystemStore from "@/stores/modules/main/system/system";

const dialogVisible = ref(false)
const isEdit = ref(false)
const editData = ref()

// 定义数据绑定
const formData = reactive<any>({
  name: '',
  leader: '',
  parentId: ''
})

// 点击确定
const systemStore = useSystemStore()
const { departmentList } = storeToRefs(systemStore)
function handleConfirmClick() {
  dialogVisible.value = false
  if (!isEdit.value) {
    systemStore.newPageDataAction('department', formData)
  } else {
    systemStore.editPageDataAction('department', editData.value.id, formData)
  }
}

// 新建或者编辑
function setDialogVisible(isNew: boolean = true, data: any = {}) {
  dialogVisible.value = true
  isEdit.value = !isNew
  editData.value = data
  for (const key in formData) {
    if (isNew) {
      formData[key] = ''
    } else {
      formData[key] = data[key]
    }
  }
}

defineExpose({
  setDialogVisible
})
</script>

<style scoped lang="less">
.form {
  padding: 10px 30px;
}
</style>
